@extends('layouts.app')

@section('title', '商圈列表')

@section('css-import')

<!-- <link rel="stylesheet" type="text/css" href="{{config('app.inlet_src')}}/assets/css/htmleaf-demo.css"> -->
<link rel="stylesheet" href="{{config('app.inlet_src')}}assets/css/baguetteBox.min.css">
<!-- <link rel="stylesheet" href="{{config('app.inlet_src')}}/assets/css/gallery-grid.css"> -->

<style type="text/css">
	.identitycardimg_sty{
		width:300px;
		display:block;
	}
	.qrcodeimg{
		cursor:pointer;
	}
	.page-s{
		display: inline-block;
		padding-bottom: 0px;
		margin: 29px 9px;
		border-radius: 4px;
		float:  right;
	}
	#l-map{height:300px;width:100%;}
#r-result{width:100%;}
.modal-backdrop{
	z-index: -1 !important;
}
</style>
@endsection

@section('content-fluid')
<div class="row">
	<!-- BASIC TABLE -->
	<div class="panel">
		<div class="panel-heading">
			<h3 class="panel-title">商圈</h3>
		</div>
		<div class="col-md-1 pull-right" style="z-index: auto;">
			<button type="button" class="btn btn-primary addcircle"><i class="fa fa-plus-square"></i> 添加</button>
		</div>
		<div class="panel-body">
			<table class="table table-hover">
				<thead>
					<tr>
						<th>#</th>
						<th>商圈名</th>
						<th>商圈区域</th>
						<th>城市</th>
						<th>添加时间</th>
						<th>店铺</th>
						<th>配送员</th>
						<th>用户数</th>
						<th>当前可用饭卡</th>
						<th>饭卡出售订单</th>
						<th>操作</th>
					</tr>
				</thead>
				<tbody>
					@foreach($circles as $v)
					<tr>
						<td>{{$v['circle_id']}}</td>
						<td class="circlename">{{$v['circle_name']}}</td>
						<td class="circleaddress">{{$v['circle_address']}}</td>
						<td class="lng_lat" style="display: none;">{{($v['lng']??'0').','.($v['lat']??'0')}}</td>
						<td class="fushe" style="display: none;">{{$v['circle_range']}}</td>
						<td class="citycircle">{{$v['city'] ?? '未设置'}}</td>
						<td>{{$v['created_at']}}</td>
						<td><a href="/shopList?circle_id={{$v['circle_id']}}"><i class="fa fa-info-circle"></i> 查看饭店</a>({{$v['shop_sum']}}家)</td>
						<td><a href="/userList?circle_id={{$v['circle_id']}}"><i class="fa fa-info-circle"></i> 配送员</a>({{$v['user_sum']}}名)</td>
						<td><a href="/userList?circle_range_id={{$v['circle_id']}}"><i class="fa fa-info-circle"></i> 用户</a>({{$v['ptuser_num']}}名)</td>
						<td>{{$v['card_num']}}</td>
						<td><a href="/cardSellorder?pay=zhifu&circle_range_id={{$v['circle_id']}}"><i class="fa fa-info-circle"></i> 查看</a></td>
						<td>
							<a href="javascript:void(0)" onclick="editcircle('{{$v['circle_id']}}',this)"><i class="fa fa-edit"></i> 修改</a>
							<a href="javascript:void(0)" onclick="delcircle('{{$v['circle_id']}}')"><i class="fa fa-trash"></i> 删除</a>
						</td>
					</tr>
					@endforeach
				</tbody>
			</table>
		</div>
		
	</div>
	<!-- END BASIC TABLE -->
</div>
<div class="modal fade" tabindex="-1" id="exampleModal" role="dialog">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title">添加商圈</h4>
      </div>
      <form action="/add/circle" method="post" id="addCircleForm">
	      <div class="modal-body">
		  	  <div class="form-group">
		      	<label for="message-text" class="control-label">商圈名称</label>
				<input type="text" name="name" class="form-control" value="" placeholder="商圈名称"/>
				<br>
				<label for="message-text" class="control-label">商圈地址</label>
				<input type="text" name="address" class="form-control" value="" placeholder="商圈地址"/>
		      </div>
	      </div>
	      <div class="modal-footer">
	        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
	        <button type="submit" class="btn btn-primary saveCateImage">保存</button>
	      </div>
      </form>
    </div>
  </div>
</div>
<div class="modal fade" id="exampleModalEdit" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" style="z-index:auto">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">修改商圈</h4>
      </div>
      <form action="/add/circle" method="post" enctype="multipart/form-data" id="confirmeditCircle">
      <div class="modal-body">
          <div class="form-group">
            <label class="control-label">商圈名称</label>
			<input type="text" name="name" value="" class="form-control form-input-control" placeholder="标题名称" alt="标题名称">
			<br>
			<label class="control-label">商圈地址</label>
			<div id="l-map"></div>
			<input type="text" id="suggestId" name="address" AUTOCOMPLETE="off" value="" class="form-control limit_days form-input-control" alt="详细地址" placeholder="详细地址">
			<div id="searchResultPanel" style="border:1px solid #C0C0C0;width:150px;height:auto; display:none;"></div>
			<br>
			<label class="control-label">辐射范围（米）</label>
			<input type="text" name="circle_range" value="" class="form-control form-input-control" placeholder="商圈覆盖范围" alt="商圈覆盖范围">
          </div>
          <input type="hidden" name="circle_id" value="">
          <input type="hidden" name="lng" value="">
		  <input type="hidden" name="lat" value="">
		  <input type="hidden" name="province" value="">
		  <input type="hidden" name="city" value="">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
        <button type="submit" class="btn btn-primary" >修改设置</button>
      </div>
      </form>
    </div>
  </div>
</div>
<img src="" class="identitycardimg identitycardimg_sty center-block hide">
@endsection

@section('js-import')
<script type="text/javascript" src="{{config('app.inlet_src')}}assets/scripts/baguetteBox.min.js"></script>
<script type="text/javascript" src="https://api.map.baidu.com/api?v=2.0&ak=vQBEj1uCOLD3MPMwoxrICDUhz7vhyR0e"></script>
@endsection

@section('js-write')
<script type="text/javascript">
	// 百度地图API功能
	function G(id) {
		return document.getElementById(id);
	}

	var map = new BMap.Map("l-map");
	map.addControl(new BMap.NavigationControl());
	map.enableScrollWheelZoom(true);
	map.centerAndZoom("石家庄",12); // 初始化地图，设置城市和地图级别。
	function addbj(lng_,lat_,fushe){
		map.clearOverlays();
		var point = new BMap.Point(lng_,lat_);  // 创建点坐标
		map.centerAndZoom(point,18); // 初始化地图,设置城市和地图级别。
		var marker = new BMap.Marker(point)
		marker.enableDragging();
		marker.addEventListener("dragend", function(e){    
		    // alert("当前位置：" + e.point.lng + ", " + e.point.lat); 
		    addbj(e.point.lng,e.point.lat,fushe)
		})
		var circle = new BMap.Circle(point,fushe,{strokeColor:"blue", strokeWeight:2, strokeOpacity:0.5});
		// polygon.enableEditing();
		// map.addOverlay(polygon);   //增加多边形
		map.addOverlay(marker);    //添加标注
		map.addOverlay(circle);
	}
	
	var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
			{"input" : "suggestId","location" : map});

	ac.addEventListener("onhighlight", function(e) {  //鼠标放在下拉列表上的事件
	var str = "";
		var _value = e.fromitem.value;
		var value = "";
		if (e.fromitem.index > -1) {
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}    
		str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;
		
		value = "";
		if (e.toitem.index > -1) {
			_value = e.toitem.value;
			value = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		}    
		str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
		G("searchResultPanel").innerHTML = str;
	});

	var myValue;
	ac.addEventListener("onconfirm", function(e) {    //鼠标点击下拉列表后的事件
	var _value = e.item.value;
		myValue = _value.province +  _value.city +  _value.district +  _value.street +  _value.business;
		G("searchResultPanel").innerHTML ="onconfirm<br />index = " + e.item.index + "<br />myValue = " + myValue;
		
		setPlace();
	});

	function setPlace(){
		map.clearOverlays();    //清除地图上所有覆盖物
		function myFun(){
			var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
			var gc = new BMap.Geocoder();
            var pointAdd = new BMap.Point(pp.lng, pp.lat);
            gc.getLocation(pointAdd, function(rs){
                //或者其他信息
                $('input[name="province"]').val(rs.addressComponents.province);
                $('input[name="city"]').val(rs.addressComponents.city);
            })
			setlnglat(pp.lng,pp.lat)
			map.centerAndZoom(pp, 18);
			var marker = new BMap.Marker(pp)
			marker.enableDragging();    
			marker.addEventListener("dragend", function(e){    
			    setlnglat(e.point.lng,e.point.lat);
			})
			map.addOverlay(marker);    //添加标注
		}
		var local = new BMap.LocalSearch(map, { //智能搜索
		  onSearchComplete: myFun
		});
		local.search(myValue);
	}

	function setlnglat(lng,lat){
		$('input[name="lng"]').val(lng);
		$('input[name="lat"]').val(lat);
	}
	$('.addcircle').click(function(){
		var model = $('#exampleModal');
		$('#exampleModal').modal();
	});
	var CouponSendParam = {
	    'dataType':'json',
	    'beforeSubmit':CouponBefore,
	    'success':CouponResponse,
	    'error':toutiaoError,
	};
	function CouponBefore(formData, jqForm, options){
	    
	}
	function CouponResponse(response) {
	    if(response.success){
	        setTimeout(function(){
	            location.href = '/get/circle/list';
	        },2000);
	        toastr.success(response.message);
	    }else{
	        toastr.error('修改失败，请联系开发人员！');
	    }
	}

	function toutiaoError(XMLHttpRequest, textStatus, errorThrown) {
		if(XMLHttpRequest.status==422){
			var RegError = XMLHttpRequest.responseJSON.errors;
			for(var o in RegError){
				for (var i = 0; i < RegError[o].length; i++) {
					toastr.error(RegError[o][i]);
				}
			}
		}
	}
	ajaxForm_('#addCircleForm', CouponSendParam);
	ajaxForm_('#confirmeditCircle', CouponSendParam);
	function delcircle(circleid){
		swal({
		  title: '您确定删除这个商圈吗', 
		  text: '删除后关联此商圈的饭店会自动解除关系', 
		  type: 'question',
		  showCancelButton: true, 
		  confirmButtonColor: '#3085d6',
		  cancelButtonColor: '#d33',
		  confirmButtonText: '确定', 
		  cancelButtonText: '取消',
		  confirmButtonClass: 'btn btn-success',
		  cancelButtonClass: 'btn btn-danger',
		  buttonsStyling: true
		}).then(function(al) {
			if(al.value){
				$.ajaxSetup({
				    headers: {
				        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
				    }
				});
				$.post('/del/circle',{circle_id:circleid},function(response){
					if(response.success){
				        setTimeout(function(){
				            location.href = '/get/circle/list';
				        },2000);
				        toastr.success(response.message);
				    }else{
				        toastr.error(response.message);
				    }
				});
			}
		});
	}
	function editcircle(circleid,this_){
		var modal = $('#exampleModalEdit');
		modal.find('input[name="circle_id"]').val(circleid);
		var cname = $(this_).parents('tr').find('.circlename').html();
		var caddress = $(this_).parents('tr').find('.circleaddress').html();
		var lng_lat = $(this_).parents('tr').find('.lng_lat').html().split(",");
		var citycircle = $(this_).parents('tr').find('.citycircle').html();
		var fushe = $(this_).parents('tr').find('.fushe').html();
		modal.find('input[name="name"]').val(cname);
		modal.find('input[name="address"]').val(caddress);
		modal.find('input[name="lng"]').val(lng_lat[0]);
		modal.find('input[name="lat"]').val(lng_lat[1]);
		modal.find('input[name="city"]').val(citycircle);
		modal.find('input[name="circle_range"]').val(fushe);
		if(lng_lat[0] != 0){
			addbj(lng_lat[0],lng_lat[1],fushe);
		}
		modal.modal();
	}

	$('#exampleModalEdit').find('input[name="circle_range"]').change(function(e){
		addbj($('#exampleModalEdit').find('input[name="lng"]').val(),$('#exampleModalEdit').find('input[name="lat"]').val(),$(this).val());
	});
</script>
@endsection